package com.gupao.javavip.rpc.framework.server;

import lombok.extern.apachecommons.CommonsLog;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;

@CommonsLog
public class ZKRegistry implements IRegistry {
    private CuratorFramework curatorFramework;

    public ZKRegistry(String registryAdd) {
        curatorFramework = CuratorFrameworkFactory.builder().
                connectString(registryAdd).sessionTimeoutMs(5000).
                retryPolicy(new ExponentialBackoffRetry(1000, 3)).
                namespace("registry")
                .build();
        curatorFramework.start();
    }

    @Override
    public void registry(String serviceId, String serviceAddress) {
        String servicePath = "/" + serviceId;
        try {
            //判断节点是否存在
            if (curatorFramework.checkExists().forPath(servicePath) == null) {
                curatorFramework.create().creatingParentsIfNeeded().
                        withMode(CreateMode.PERSISTENT).forPath(servicePath);
            }

            //serviceAddress: ip:port
            String addressPath = servicePath + "/" + serviceAddress;
            curatorFramework.create().withMode(CreateMode.EPHEMERAL).forPath(addressPath);
            log.info("服务[" + addressPath + "]注册成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
